package cn.supermarket.controller.service;

import cn.supermarket.common.annotation.Log;
import cn.supermarket.common.core.controller.BaseController;
import cn.supermarket.common.core.entity.Result;
import cn.supermarket.common.core.page.TableDataInfo;
import cn.supermarket.common.enums.BusinessType;
import cn.supermarket.common.utils.SecurityUtils;
import cn.supermarket.system.dto.TSalesDTO;
import cn.supermarket.system.entity.TProduct;
import cn.supermarket.system.entity.TSales;
import cn.supermarket.system.entity.TWarehouse;
import cn.supermarket.system.result.TSalesResult;
import cn.supermarket.system.service.TSalesService;
import cn.supermarket.system.service.TWarehouseService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @Author yp
 * @Date 2025/3/13:09:27
 */
@RestController
@RequestMapping("/service/sales")
@Api(value = "销售模块", tags = "销售模块")
public class TSalesController extends BaseController {

    @Autowired
    private TSalesService tSalesService;

    @Autowired
    private TWarehouseService tWarehouseService;

    @GetMapping("/list")
    public TableDataInfo list(TSalesDTO tSalesDTO)
    {
        List<TSalesResult> list = tSalesService.pageList(tSalesDTO);
        return getDataTable(list);
    }


    /**
     * 新增
     */
    @PreAuthorize("@ss.hasPermi('service:sales:add')")
    @Log(title = "商品管理", businessType = BusinessType.INSERT)
    @PostMapping
    public Result add(@Validated @RequestBody TSales tSales)
    {
        TWarehouse tWarehouse = tWarehouseService.getWare(tSales.getCommodityNumber()).get(0);
        if (tWarehouse.getCount()<tSales.getSalesVolume()){
            return Result.error("库存不足，请补充库存");
        }
        tWarehouse.setCount(tWarehouse.getCount() - tSales.getSalesVolume());
        tWarehouseService.updateById(tWarehouse);
        tSales.setSalesAmount(new BigDecimal(tSales.getUnitPrice()).multiply(new BigDecimal(tSales.getSalesVolume())).setScale(2,BigDecimal.ROUND_HALF_UP));
        tSales.setCreateBy(SecurityUtils.getUsername());
        tSales.setUpdateBy(SecurityUtils.getUsername());
        tSales.setUpdateTime(new Date());
        return toAjax(tSalesService.save(tSales));
    }
}
